package com.yml.mall.interceptor;


import com.yml.mall.currentexception.UserLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.yml.mall.consts.myConst.CURRENT_USER;

/**
 * @ClassName MyInterceptor
 * @Author Administrator
 * @Date 2020/4/7   15:57
 */
@Slf4j
public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle....");
        if(request.getSession().getAttribute(CURRENT_USER)==null)
        {
            log.info("未登录");
            //1.写入错误信息 不推荐这样用 2.可以用统一异常处理
            /*
            1.response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().print(JSON.toJSON(ResponseVO.error(ResponseEnum.NOT_LOGIN)));
            response.getWriter().write(JSON.toJSON(ResponseVO.error(ResponseEnum.NOT_LOGIN)).toString());
            */
            //2
            throw new UserLoginException();
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
